#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h>

#define MAX 10000000
int N;
double step;            //must be odd
double sum = 0;

void* thread(void* arg)
{
    double* result = malloc(sizeof(double));
    *result = 0;
    double* p = arg;
    double begin = *p * step*2 + 1;
    for (int i = 0; i < step; i++)
    {
        if (i&1)
            *result -= 1/begin;
        else
            *result += 1/begin;
        begin+=2;
    }

    return result;
}

int main(int argc, char** argv)
{
    assert(argc == 2);  
    N = atoi(argv[1]);

    int s = MAX/N;
    if (s&1)
        s++;
    step = s;

    double array[N];
    for (int i = 0; i < N; i++)
        array[i] = i;

    pthread_t worker[N];
    for (int i = 0; i < N; i++)
        pthread_create(worker+i, NULL, thread, array+i);

    for (int i = 0; i < N; i++)
    {
        double* result;
        pthread_join(worker[i], (void **)&result);

        sum += *result;
        free(result);
    }

    printf("PI = %f", sum*4);
}